package com.example.afinal;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.icu.util.Calendar;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private boolean hide=false;

    private ListView mListView;
    private Button btn_calendar;
    private Button btn_see;
    private Button btn_stat;
    private Button btn_delete;
    private ImageButton btn_book_keeping;
    private int num = 0;    // 账单数目
    private ArrayList<Integer> years =new ArrayList();
    private ArrayList<Integer> months =new ArrayList();
    private ArrayList<Integer> dayOfMonths =new ArrayList();
    private ArrayList<Integer> types = new ArrayList();
    private ArrayList<String> remarks = new ArrayList();
    private ArrayList<Float> accounts = new ArrayList();
    MyHelper myHelper;

    private TextView tv_date;
    private TextView tv_income;
    private TextView tv_outcome;
    private TextView tv_balance;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = findViewById(R.id.lv);
        btn_calendar = findViewById(R.id.btn_calendar);
        btn_see = findViewById(R.id.btn_see);
        btn_stat = findViewById(R.id.btn_stat);
        btn_book_keeping = findViewById(R.id.btn_book_keeping);
        btn_delete=findViewById(R.id.btn_delete);

        tv_date = findViewById(R.id.tv_date);
        tv_income = findViewById(R.id.tv_income);
        tv_outcome = findViewById(R.id.tv_outcome);
        tv_balance = findViewById(R.id.tv_balance);

        btn_calendar.setOnClickListener(this);
        btn_see.setOnClickListener(this);
        btn_stat.setOnClickListener(this);
        btn_book_keeping.setOnClickListener(this);
        btn_delete.setOnClickListener(this);

        GlobalVariables.getCurrentDateActivity();
        updateUI();
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onResume() {
        updateUI();
        super.onResume();
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void updateUI(){
        initDatabase(); // 初始化数据库

        tv_date.setText(GlobalVariables.selectYear+"."+GlobalVariables.selectMonth+"."+GlobalVariables.selectDayOfMonth);
        if(hide)
        {
            tv_income.setText("****.**");
            tv_outcome.setText("****.**");
            tv_balance.setText("****.**");
        }
        else{
            float income = getSumMoneyOneMonth(GlobalVariables.selectYear, GlobalVariables.selectMonth, false);
            float outcome = getSumMoneyOneMonth(GlobalVariables.selectYear, GlobalVariables.selectMonth, true);
            tv_income.setText(String.format("%.2f", income));
            tv_outcome.setText(String.format("%.2f", outcome));
            tv_balance.setText(String.format("%.2f", income - outcome));
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.btn_calendar:
                chooseDateActivity(v);
                break;
            case R.id.btn_see:
                if(hide==true){
                    btn_see.setBackground(getDrawable(R.drawable.eye_btn));
                    hide=false;
                }else{
                    btn_see.setBackground(getDrawable(R.drawable.eye_closed_btn));
                    hide=true;
                }
                updateUI();
                break;
            case R.id.btn_stat:
                startActivity(new Intent(this,StatActivity.class));
                break;
            case R.id.btn_book_keeping:
                startActivity(new Intent(this,BookKeepingActivity.class));
                break;
            case R.id.btn_delete:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("警告");
                builder.setMessage("这将删除所有记账数据");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("点了确定");
                        SQLiteDatabase db;
                        db = myHelper.getWritableDatabase();
                        db.delete("accountBook", null, null);
                        db.close();
                        updateUI();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                //一样要show
                builder.show();
            break;
        }
    }
    private void initDatabase(){
        myHelper = new MyHelper(this);
        SQLiteDatabase db;
        db = myHelper.getReadableDatabase();
        Cursor cursor = db.query("accountBook", null, null, null, null, null, null);
        num = cursor.getCount();
        if (num != 0) {
            cursor.moveToFirst();
            years.add(cursor.getInt(1));
            months.add(cursor.getInt(2));
            dayOfMonths.add(cursor.getInt(3));
            types.add(cursor.getInt(4));
            accounts.add(cursor.getFloat(5));
            remarks.add(cursor.getString(6));
        }
        while (cursor.moveToNext())
        {
            years.add(cursor.getInt(1));
            months.add(cursor.getInt(2));
            dayOfMonths.add(cursor.getInt(3));
            types.add(cursor.getInt(4));
            accounts.add(cursor.getFloat(5));
            remarks.add(cursor.getString(6));
        }
        cursor.close();
        db.close();

        Collections.reverse(years);
        Collections.reverse(months);
        Collections.reverse(dayOfMonths);
        Collections.reverse(types);
        Collections.reverse(accounts);
        Collections.reverse(remarks);

        MainActivity.MyBaseAdapter mAdapter = new MainActivity.MyBaseAdapter();  //创建一个Adapter 的实例
        mListView.setAdapter(mAdapter);  //设置Adapter
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {        //点击listView，跳转到统计信息界面
                GlobalVariables.selectID = num-(int)id-1;
                changeToDetailedInformationActivity();
            }
        });
    }
    private void changeToDetailedInformationActivity()
    {
        startActivity(new Intent(this,DetailedInformationActivity.class));
    }
    public float getSumMoneyOneMonth(int _year,int _month,boolean _type)    // _year为年份, _month为月份, _type为True表示支出, _type为False表示收入
    {
        float ans=0;

        myHelper = new MyHelper(this);
        SQLiteDatabase db;
        db = myHelper.getReadableDatabase();
        Cursor cursor = db.query("accountBook", null, null, null, null, null, null);
        num = cursor.getCount();
        if (num == 0)
        {
            return 0;
        }
        else{
            cursor.moveToFirst();
            if(_type==true && cursor.getInt(4)<20 && cursor.getInt(1)==_year && cursor.getInt(2)==_month )
            {
                ans+=cursor.getFloat(5);
            }
            else if(_type==false && cursor.getInt(4)>=20 && cursor.getInt(1)==_year && cursor.getInt(2)==_month )
            {
                ans+=cursor.getFloat(5);
            }
        }
        while (cursor.moveToNext()) {
            if(_type==true && cursor.getInt(4)<20 && cursor.getInt(1)==_year && cursor.getInt(2)==_month )
            {
                ans+=cursor.getFloat(5);
            }
            else if(_type==false && cursor.getInt(4)>=20 && cursor.getInt(1)==_year && cursor.getInt(2)==_month )
            {
                ans+=cursor.getFloat(5);
            }
        }
        cursor.close();
        db.close();
        return ans;
    }

    class MyBaseAdapter extends BaseAdapter {
        //得到item 的总数
        @Override
        public int getCount() {
//返回ListView Item 条目的总数
            return num;
        }
        //得到Item 代表的对象
        @Override
        public Object getItem(int position) {
//返回ListView Item 条目代表的对象
            return types.get(position);
        }
        //得到Item 的id
        @Override
        public long getItemId(int position) {
//返回ListView Item 的id
            return position;
        }
        //得到Item 的View 视图
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
//将list_item.xml 文件找出来并转换成View 对象
            View view = View.inflate(MainActivity.this,
                    R.layout.list_item, null);
            if(hide)
            {
                TextView item_tv_date = (TextView) view.findViewById(R.id.item_tv_date);
                item_tv_date.setText("****年**月**日");

                TextView item_tv_type_name = (TextView) view.findViewById(R.id.item_tv_type_name);
                item_tv_type_name.setText("****");

                TextView item_tv_remarks = (TextView) view.findViewById(R.id.item_tv_remarks);
                item_tv_remarks.setText("");


                TextView item_tv_account = (TextView) view.findViewById(R.id.item_tv_account);
                item_tv_account.setTextColor(Color.rgb(102, 102, 102));
                item_tv_account.setText("****.**");

                ImageView item_tv_type_icon = (ImageView) view.
                        findViewById(R.id.item_tv_type_icon);
                item_tv_type_icon.setBackgroundResource(R.drawable.unknown);
            }else {
                TextView item_tv_date = (TextView) view.findViewById(R.id.item_tv_date);
                item_tv_date.setText(years.get(position) + "年" + months.get(position) + "月" + dayOfMonths.get(position) + "日");

                TextView item_tv_type_name = (TextView) view.findViewById(R.id.item_tv_type_name);
                item_tv_type_name.setText(GlobalVariables.typeIDTypeName(types.get(position)));

                TextView item_tv_remarks = (TextView) view.findViewById(R.id.item_tv_remarks);
                item_tv_remarks.setText(remarks.get(position));


                TextView item_tv_account = (TextView) view.findViewById(R.id.item_tv_account);
                if (types.get(position) < 20) {
                    item_tv_account.setTextColor(Color.rgb(204, 102, 102));
                    item_tv_account.setText("-" + String.format("%.2f", accounts.get(position)));
                } else {
                    item_tv_account.setTextColor(Color.rgb(102, 204, 102));
                    item_tv_account.setText("+" + String.format("%.2f", accounts.get(position)));
                }

                ImageView item_tv_type_icon = (ImageView) view.
                        findViewById(R.id.item_tv_type_icon);
                item_tv_type_icon.setBackgroundResource(GlobalVariables.typeIDTypeIcon(types.get(position)));
            }
            return view;
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void chooseDateActivity(View v){
        Calendar calendar=Calendar.getInstance();
        new DatePickerDialog( this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                GlobalVariables.selectYear = year;
                GlobalVariables.selectMonth = month+1;
                GlobalVariables.selectDayOfMonth = dayOfMonth;
                updateUI();
            }
        }
                ,calendar.get(Calendar.YEAR)
                ,calendar.get(Calendar.MONTH)
                ,calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
}
